package com.central.apps.handler.contract;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.common.exception.service.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ContracttypeHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_contracttype".equals(objName) && !isUpdate) {
            String typename = MapUtils.getString(data, "typename");
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_contracttype where typename = '" + typename + "' and delflag =0");
            if (CollectionUtils.isNotEmpty(list)) {
                throw new ServiceException("合同类型已存在，请修改类型名称再保存");
            }
        }
        if ("gq_contracttypetwo".equals(objName) && !isUpdate) {
            String typename = MapUtils.getString(data, "typename");
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_contracttypetwo where typename = '" + typename + "' and delflag =0");
            if (CollectionUtils.isNotEmpty(list)) {
                throw new ServiceException("合同类型已存在，请修改类型名称再保存");
            }
        }
    }

    /*
    * 删除前判断 合同类型是否被合同模板引用
    * */
    @Override
    public String validateDelete(String app, String objName, Long id) throws Exception {
        if("gq_contracttype".equals(objName)){
            List<Map<String,Object>> list = handlerService.findBySql(" select * from gq_contemplate where typeid = "+id+" and status not in ('已作废','新建')");
            if(CollectionUtils.isNotEmpty(list)){
                //throw new ServiceException("合同类型已经被合同模板引用，无法删除");
                return "合同类型已经被合同模板引用，无法删除";
            }
        }
//        if("gq_contracttype".equals(objName)){
//            //List<Map<String,Object>> list = handlerService.findBySql("select id from gq_contracttype where pid = "+id);
//            //for (Map<String, Object> map : list) {
//                List<Map<String,Object>> list2 = handlerService.findBySql(" select * from gq_contemplate where typeid = "+id+" and status !='已作废'");
//                if(CollectionUtils.isNotEmpty(list2)){
//                    //throw new ServiceException("合同类型已经被合同模板引用，无法删除");
//                    return "合同类型已经被合同模板引用，无法删除";
//                }
//           // }
//        }

        return super.validateDelete(app, objName, id);
    }

}
